//
//  AccountViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/6/14.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//
// TODO: Do not delete account if it is associated by transactions.
//

#import "AccountViewController.h"

@interface AccountViewController ()

@end

@implementation AccountViewController

@synthesize account;
@synthesize loadID;
@synthesize loadType;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.delegate = self;
        account = nil;
        accounts = [[NSMutableArray alloc] init];
        loadID = 0;
        loadType = AccountTypeAll;
        self.tableView.tag = RichTableViewTagAccount;
        [self initAccountTypePicker];
        [self initAccountPropertyPicker];
        [self initCurrencyPicker];
        [self initInputToolbar:RichInputToolbarButtonDefaultSet];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSUInteger currId = account.accountId;
    
    if (self.mode == RichTableModeListReadonly) {
        if (loadID > 0)
            [[RichDelegate core] accounts:accounts loadWithID:loadID];
        else
            [[RichDelegate core] accounts:accounts loadWithType:loadType];
    }
    else {
        [[RichDelegate core] accounts:accounts loadWithType:AccountTypeAll];
    }
    
    [[RichDelegate core] accountsCalculateBalance:accounts];
    
    if (currId > 0) {
        /* Re-assign current account */
        for (RichAccount *a in accounts) {
            if (a.accountId == currId) {
                if (account)
                    [account release];
                account = [a retain];
                break;
            }
        }
    }
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)accounts
{
    return accounts;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    // TODO: [Account] Remove invisible accounts
    
    if (self.mode == RichTableModeListEditable || self.mode == RichTableModeListReadonly)
        return [accounts count];
    else {
        if (account.type == AccountTypeCreditCards)
            return 7;
        else
            return 6;
    }
}

enum {
    AccountNameRowIndex,
    AccountTypeRowIndex,
    AccountCurrencyRowIndex,
    AccountInitBalanceRowIndex,
    AccountPropertyRowIndex,
    AccountCreditCardAPRRowIndex,
    AccountDescriptionRowIndex
};

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (self.mode == RichTableModeCreate || self.mode == RichTableModeUpdate) {
        NSUInteger currentRow = [indexPath row];
        
        if (account.type != AccountTypeCreditCards)
            if (currentRow >= AccountCreditCardAPRRowIndex)
                ++currentRow;
        
        tableCellStyle = RichTableCellStyleTextfield;
        RichTableViewTextfieldCell *textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
        textfieldCell.textfield.placeholder = nil;
        cell = textfieldCell;
        
        switch (currentRow) {
            case AccountNameRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Name");
                textfieldCell.textfield.placeholder = RichLocaleString(@"Account Name");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDefault;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.autocorrectionType = UITextAutocorrectionTypeNo;
                textfieldCell.textfield.autocapitalizationType = UITextAutocapitalizationTypeWords;
                textfieldCell.textfield.text = account.name;
                break;
            
            case AccountTypeRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Type");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = accountTypePicker;
                textfieldCell.textfield.text = [[RichDelegate core] accountTypeToString:account.type];
                break;
            
            case AccountCurrencyRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Currency");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = currencyPicker;
                textfieldCell.textfield.text = account.currencyCode;
                break;
            
            case AccountInitBalanceRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Initail Balance");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:account.currencyCode], account.initialBalance];
                break;
            
            case AccountPropertyRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Property");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = accountPropertyPicker;
                textfieldCell.textfield.text = [[RichDelegate core] accountPropertyToString:account.property];
                break;
            
            case AccountCreditCardAPRRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Annual Percentage Rate");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                textfieldCell.textfield.text = [NSString stringWithFormat:@"%2.3f %%", account.creditCardAPR];
                break;
            
            case AccountDescriptionRowIndex:
                textfieldCell.textLabel.text = RichLocaleString(@"Description");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDefault;
                textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                textfieldCell.textfield.text = account.description;
                break;
        }
    }
    else if (self.mode == RichTableModeListEditable) {
        tableCellStyle = RichTableCellStyleValue;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        RichAccount *_account = [accounts objectAtIndex:[indexPath row]];
        
        if (_account) {
            cell.textLabel.text = [_account name];
            cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:_account.initialBalance code:_account.currencyCode];
        }
    }
    else if (self.mode == RichTableModeListReadonly) {
        tableCellStyle = RichTableCellStyleDefault;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        RichAccount *_account = [accounts objectAtIndex:[indexPath row]];
        
        if (_account) {
            cell.textLabel.text = [_account name];
            cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:_account.balance code:_account.currencyCode];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *accountName = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
        RichAccount *_account = [[RichDelegate core] accounts:accounts findAccountByName:accountName];
        
        if (_account) {
            [[RichDelegate core] accounts:accounts delete:_account.accountId];

            // Delete the row from the data source
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    
    [super tableView:tableView commitEditingStyle:editingStyle forRowAtIndexPath:indexPath];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing)
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleNone;
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.mode == RichTableModeListReadonly) {
        if (account)
            [account release];
        account = [[accounts objectAtIndex:[indexPath row]] retain];
        [self.callerDelegate tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath];
    }
    else if (self.mode == RichTableModeListEditable) {
        AccountViewController *avc = [[AccountViewController alloc] initWithStyle:UITableViewStylePlain];
        avc.navigator = self.navigator;
        avc.account = [accounts objectAtIndex:[indexPath row]];
        avc.mode = RichTableModeUpdate;
        [self.navigator pushViewController:avc animated:YES];
        [avc release];
    }
}

#pragma mark - Textfield delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    if (account == nil && self.mode == RichTableModeCreate)
        account = [[RichAccount alloc] init];
    
    NSUInteger currentRow = textField.tag;
    NSInteger i;
    double apr;
    
    if (account.type != AccountTypeCreditCards)
        if (currentRow >= AccountCreditCardAPRRowIndex)
            ++currentRow;
    
    switch (currentRow) {
        case AccountNameRowIndex:
            break;
            
        case AccountTypeRowIndex:
            if ([textField.text isEqualToString:@""])
                textField.text = [accountTypes objectAtIndex:0];
            
            for (i = 0; i < [accountTypes count]; i++) {
                if ([(NSString *)[accountTypes objectAtIndex:i] isEqualToString:textField.text]) {
                    [accountTypePicker selectRow:i inComponent:0 animated:NO];
                    [accountTypePicker reloadAllComponents];
                    break;
                }
            }
            break;
            
        case AccountCurrencyRowIndex:
            if ([textField.text isEqualToString:@""])
                textField.text = [[[[RichDelegate core] currencies] allKeys] objectAtIndex:0];
            
            for (i = 0; i < [[[[RichDelegate core] currencies] allKeys] count]; i++) {
                if ([[[[[RichDelegate core] currencies] allKeys] objectAtIndex:i] isEqualToString:textField.text]) {
                    [currencyPicker selectRow:i inComponent:0 animated:NO];
                    break;
                }
            }
            break;
            
        case AccountInitBalanceRowIndex:
            if ([textField.text isEqualToString:@"0"])
                textField.text = @"";
            break;
            
        case AccountPropertyRowIndex:
            if ([textField.text isEqualToString:@""])
                textField.text = [[RichDelegate core] accountPropertyToString:0];
            
            [accountPropertyPicker selectRow:[[RichDelegate core] accountPropertyFromString:textField.text] inComponent:0 animated:NO];
            [accountPropertyPicker reloadAllComponents];
            break;
            
        case AccountCreditCardAPRRowIndex:
            apr = [(NSString *)[[textField.text componentsSeparatedByString:@"%"] objectAtIndex:0] doubleValue];
            if (apr == 0.0f)
                textField.text = @"";
            else
                textField.text = [NSString stringWithFormat:@"%2.3f", apr];
            break;
            
        case AccountDescriptionRowIndex:
            break;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [super textFieldDidEndEditing:textField];
    
    NSUInteger currentRow = textField.tag;
    
    if (account.type != AccountTypeCreditCards)
        if (currentRow >= AccountCreditCardAPRRowIndex)
            ++currentRow;
    
    switch (currentRow) {
        case AccountNameRowIndex:
            account.name = textField.text;
            break;
            
        case AccountTypeRowIndex:
            account.type = (AccountType)[[RichDelegate core] accountTypeFromString:textField.text];
            if (account.type == AccountTypeCreditCards) {
                if ([self.tableView numberOfRowsInSection:0] == 6) {
                    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:AccountCreditCardAPRRowIndex inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationAutomatic];
                    /* Reload to update tag number of last textfield cell */
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:AccountDescriptionRowIndex inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationAutomatic];
                }
            }
            else {
                account.creditCardAPR = 0.0f;
                if ([self.tableView numberOfRowsInSection:0] == 7) {
                    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:AccountCreditCardAPRRowIndex inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationAutomatic];
                    /* Reload to update tag number of last textfield cell */
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:AccountCreditCardAPRRowIndex inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationAutomatic];
                }
            }
            
            break;
        
        case AccountCurrencyRowIndex:
            account.currencyCode = textField.text;
            // FIXME: have to let initial balance become first responder
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:AccountInitBalanceRowIndex inSection:0]]
                                  withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        
        case AccountInitBalanceRowIndex:
            if (account.currencyCode)
                textField.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:account.currencyCode], [textField.text doubleValue]];
            account.initialBalance = [textField.text doubleValue];
            break;
            
        case AccountPropertyRowIndex:
            account.property= (AccountProperty)[[RichDelegate core] accountPropertyFromString:textField.text];
            break;
        
        case AccountCreditCardAPRRowIndex:
            account.creditCardAPR = [[NSString stringWithFormat:@"%2.3f", [textField.text doubleValue]] doubleValue];
            textField.text = [NSString stringWithFormat:@"%2.3f %%", account.creditCardAPR];
            break;
            
        case AccountDescriptionRowIndex:
            account.description = textField.text;
            break;
    }
}

#pragma mark - RichTableViewController Delegate

- (void)didPressCreate
{
    AccountViewController *avc = [[AccountViewController alloc] initWithStyle:UITableViewStylePlain];
    avc.navigator = self.navigator;
    avc.mode = RichTableModeCreate;
    [self.navigator pushViewController:avc animated:YES];
    [avc release];
}

- (void)didPressCreateDone
{
    if ([[RichDelegate core] accounts:accounts create:account] > 0) {
        [accountTypePicker selectRow:0 inComponent:0 animated:YES];
        [currencyPicker selectRow:0 inComponent:0 animated:YES];
        [accountPropertyPicker selectRow:0 inComponent:0 animated:YES];
        
        [account release];
        account = nil;
    }
    else {
        NSLog(@"Create account failed");
        // TODO: prompt error message
    }
    
    [self.navigator popViewControllerAnimated:YES];
}

- (void)didPressUpdateDone
{
    if ([[RichDelegate core] accounts:accounts update:account] < 0) {
        NSLog(@"Update account failed");
        // TODO: prompt error message
    }
    
    [self.navigator popViewControllerAnimated:YES];
}

@end
